package org.dromara.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.customer.domain.TaOrderDetail;
import org.dromara.customer.domain.bo.TaOrderDetailBo;
import org.dromara.customer.domain.bo.TaStoreOrdersDetailBo;
import org.dromara.customer.mapper.TaOrderDetailMapper;
import org.dromara.customer.mapper.TaShoppingCartMapper;
import org.dromara.merchants.api.RemoteGoodsService;
import org.springframework.stereotype.Service;
import org.dromara.customer.domain.bo.TaOrdersBo;
import org.dromara.customer.domain.vo.TaOrdersVo;
import org.dromara.customer.domain.TaOrders;
import org.dromara.customer.mapper.TaOrdersMapper;
import org.dromara.customer.service.ITaOrdersService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 订单Service业务层处理
 *
 * @author xiyin321
 * @date 2024-07-09
 */
@RequiredArgsConstructor
@Service
public class TaOrdersServiceImpl implements ITaOrdersService {

    private final TaOrdersMapper baseMapper;
    private final TaOrderDetailMapper orderDetailMapper;
    private final TaShoppingCartMapper shoppingCartMapper;
    @DubboReference
    private final RemoteGoodsService remoteGoodsService;

    /**
     * 查询订单
     */
    @Override
    public TaOrdersVo queryById(Long ordersId) {
        TaOrdersVo vo = baseMapper.selectOrderById(ordersId);
        vo.setGoodsList(orderDetailMapper.selectVoList(Wrappers.<TaOrderDetail>lambdaQuery().eq(TaOrderDetail::getOrdersId, ordersId)));
        return vo;
    }

    /**
     * 查询订单列表
     */
    @Override
    public TableDataInfo<TaOrdersVo> queryPageList(TaOrdersBo bo, PageQuery pageQuery) {
        Page<TaOrdersVo> result = baseMapper.selectOrderPage(pageQuery.build(), this.buildQueryWrapper(bo));
        result.getRecords().forEach(item -> {
            item.setGoodsList(orderDetailMapper.selectVoList(Wrappers.<TaOrderDetail>lambdaQuery().eq(TaOrderDetail::getOrdersId, item.getOrdersId())));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询订单列表
     */
    @Override
    public List<TaOrdersVo> queryList(TaOrdersBo bo) {
        LambdaQueryWrapper<TaOrders> lqw = buildLambdaQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /*构建查询条件*/
    private Wrapper<TaOrders> buildQueryWrapper(TaOrdersBo bo) {
        QueryWrapper<TaOrders> wrapper = Wrappers.query();
        wrapper.eq("o.del_flag", "0")
            .eq(StringUtils.isNotBlank(bo.getStatus()), "o.status", bo.getStatus());
        return wrapper;
    }

    private LambdaQueryWrapper<TaOrders> buildLambdaQueryWrapper(TaOrdersBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TaOrders> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStatus() != null, TaOrders::getStatus, bo.getStatus());
        lqw.eq(bo.getUserId() != null, TaOrders::getUserId, bo.getUserId());
        lqw.eq(bo.getOrderTime() != null, TaOrders::getOrderTime, bo.getOrderTime());
        lqw.eq(bo.getCheckoutTime() != null, TaOrders::getCheckoutTime, bo.getCheckoutTime());
        lqw.eq(bo.getPayMethod() != null, TaOrders::getPayMethod, bo.getPayMethod());
        lqw.eq(bo.getPayStatus() != null, TaOrders::getPayStatus, bo.getPayStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getCancelReason()), TaOrders::getCancelReason, bo.getCancelReason());
        lqw.eq(StringUtils.isNotBlank(bo.getRejectionReason()), TaOrders::getRejectionReason, bo.getRejectionReason());
        lqw.eq(bo.getCancelTime() != null, TaOrders::getCancelTime, bo.getCancelTime());
        lqw.eq(bo.getEstimatedDeliveryTime() != null, TaOrders::getEstimatedDeliveryTime, bo.getEstimatedDeliveryTime());
        lqw.eq(bo.getDeliveryStatus() != null, TaOrders::getDeliveryStatus, bo.getDeliveryStatus());
        lqw.eq(bo.getDeliveryTime() != null, TaOrders::getDeliveryTime, bo.getDeliveryTime());
        lqw.eq(bo.getPackAmount() != null, TaOrders::getPackAmount, bo.getPackAmount());
        lqw.eq(bo.getTablewareNumber() != null, TaOrders::getTablewareNumber, bo.getTablewareNumber());
        lqw.eq(bo.getTablewareStatus() != null, TaOrders::getTablewareStatus, bo.getTablewareStatus());
        return lqw;
    }

    /**
     * 新增订单
     */
    @Override
    public Boolean insertByBo(TaOrdersBo bo) {
        List<TaStoreOrdersDetailBo> goodsList = bo.getGoodsList();
        TaOrders add = MapstructUtils.convert(bo, TaOrders.class);
        add.setUserId(LoginHelper.getUserId());
        add.setOrderTime(new Date());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        BigDecimal totalAmount = new BigDecimal(0);

        // 假设 goodsList 是一个List集合
        for (TaStoreOrdersDetailBo item : goodsList) {
            List<TaOrderDetailBo> goods = item.getGoodsList();
            for (TaOrderDetailBo good : goods) {
                good.setOrdersId(add.getOrdersId());
                good.setStoreId(item.getStoreId());
                good.setStoreName(item.getStoreName());
                String price = remoteGoodsService.queryGoodsById(good.getGoodsId()).getPrice();
                BigDecimal amount = new BigDecimal(price).multiply(new BigDecimal(good.getNumber()));
                good.setAmount(String.valueOf(amount));
                totalAmount = totalAmount.add(amount);
                if (good.getId() != null) {
                    shoppingCartMapper.deleteById(good.getId());
                }
            }
            orderDetailMapper.insertBatch(MapstructUtils.convert(goods, TaOrderDetail.class));
        }

        if (flag) {
            bo.setOrdersId(add.getOrdersId());
        }
        System.out.println(totalAmount);
        /*更新订单orderAmount*/
        baseMapper.updateAmountById(String.valueOf(totalAmount), add.getOrdersId());

        return flag;
    }

    /**
     * 修改订单
     */
    @Override
    public Boolean updateByBo(TaOrdersBo bo) {
        TaOrders update = MapstructUtils.convert(bo, TaOrders.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TaOrders entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
